package com.gjxx.system.service.impl;

import com.gjxx.common.config.MinioConfig;
import com.gjxx.common.utils.file.FileUploadUtils;
import com.gjxx.common.utils.file.FileUtils;
import com.gjxx.system.domain.vo.FileVo;
import com.gjxx.system.service.ISysFileService;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

/**
 * Minio 文件存储
 *
 * @author gjxx
 */
@Service
@Primary
@Slf4j
public class MinioSysFileServiceImpl implements ISysFileService {
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient minioClient;

    /**
     * Minio文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file,String fileNameHead) throws Exception {
        String fileName = FileUploadUtils.extractFilename(file,fileNameHead);
        InputStream inputStream = file.getInputStream();
        PutObjectArgs args = PutObjectArgs.builder().bucket(minioConfig.getBucketName())
                .object(fileName).stream(inputStream, file.getSize(), -1)
                .contentType(file.getContentType()).build();
        minioClient.putObject(args);
        IOUtils.closeQuietly(inputStream);
        return "/" + minioConfig.getBucketName() + "/" + fileName;
    }

    @Override
    public FileVo uploadFileNew(MultipartFile file,String fileNameHead) throws Exception {
        FileVo fileVo = new FileVo();
        String fileName = this.uploadFile(file,fileNameHead);
        fileVo.setFileName(fileName);
        fileVo.setUrl(minioConfig.getBaseUrl() + fileName);
        fileVo.setDomain(minioConfig.getBaseUrl());
        fileVo.setNewFileName(FileUtils.getName(fileName));
        fileVo.setOriginalFilename(file.getOriginalFilename());
        return fileVo;
    }

    @Override
    public String uploadFile(byte[] fileBytes, String fileNameHead) throws Exception {
        InputStream inputStream = new ByteArrayInputStream(fileBytes);
        MultipartFile multipartFile = new MockMultipartFile(
                ContentType.APPLICATION_OCTET_STREAM.toString(),fileNameHead+".png","image/png", inputStream);
        return this.uploadFile(multipartFile,fileNameHead);
    }
}
